//package com.yowasa.xiuxian.config;
//
//import com.yowasa.xiuxian.entity.bot.Gateway;
//import com.yowasa.xiuxian.service.QQChannelService;
//import com.yowasa.xiuxian.service.WebSocketService;
//import com.yowasa.xiuxian.websocket.CustomWebSocketClient;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.concurrent.BasicThreadFactory;
//import org.java_websocket.client.WebSocketClient;
//import org.java_websocket.enums.ReadyState;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//
//import java.net.URI;
//import java.util.concurrent.ScheduledExecutorService;
//import java.util.concurrent.ScheduledThreadPoolExecutor;
//import java.util.concurrent.TimeUnit;
//
//
//@Configuration
//@Slf4j
//public class WebSocketConfig {
//
//    @Autowired
//    QQChannelService QQChannelService;
//    @Value("Bot ${bot.id}.${bot.token}")
//    String token;
//    @Autowired
//    private WebSocketService webSocketService;
//
//    private ScheduledExecutorService executorService;
//
//    @Bean
//    public WebSocketClient webSocketClient() {
//        Gateway gateway = QQChannelService.gateway();
//        URI uri = URI.create(gateway.getUrl());
//        CustomWebSocketClient client = new CustomWebSocketClient(uri, token, webSocketService);
//        client.connect();
//        /**
//         * 重连机制
//         * */
//        executorService = new ScheduledThreadPoolExecutor(1,
//                new BasicThreadFactory.Builder().namingPattern("websocket-reconnect-schedule-pool-%d").daemon(true).build());
//        executorService.scheduleAtFixedRate(new Runnable() {
//            @Override
//            public void run() {
//                try{
//                    if(client.getReadyState()!= ReadyState.OPEN) {
//                        if(client.getReadyState()== ReadyState.NOT_YET_CONNECTED) {
//                            if(client.isClosed()) {
//                                log.info("连接关闭,正在重新连接中……");
//                                client.reconnect();
//                            }else{
//                                log.info("建立连接中……");
//                                client.connect();
//                            }
//                        }else if( client.getReadyState() == ReadyState.CLOSED){
//                            log.info("连接关闭,正在重新连接中……");
//                            client.reconnect();
//                        }
//                    }
//                }catch(Exception e) {
//                    log.error("连接异常,等待下个周期重新连接……");
//                }
//            }
//        },0,6000, TimeUnit.MILLISECONDS);
//        return client;
//    }
//}
